package com.yoofn.framework.activity

import android.view.KeyEvent
import android.widget.LinearLayout
import com.just.library.AgentWeb
import com.yanzhenjie.nohttp.rest.Response
import com.yoofn.framework.R
import com.yoofn.framework.config.ViewConfig
import com.yoofn.framework.databinding.ActivityWebviewBinding
import com.yoofn.framework.http.HttpJavaScriptInterface


/**
 *
 * Created by kalshen on 17/6/2.
 * @描述 展示web 界面主要的activity
 */
class WebActivity : BaseActivity<ActivityWebviewBinding>() {
    override fun setupConfig(): ViewConfig {
        return ViewConfig(R.layout.activity_webview)
    }

    companion object {
        /**
         * webView 的url地址
         */
        val WEB_URL = "web_url"

        /**
         * webView 调用android的主方法名
         */
        val WEB_METHOD = "android"
    }

    private var agentWeb: AgentWeb? = null

    override fun initView() {
        with(contentView) {
            //配置agentWeb
            agentWeb = AgentWeb.with(this@WebActivity)
                    .setAgentWebParent(llWeb, LinearLayout.LayoutParams(-1, -1))
                    .useDefaultIndicator()
                    .defaultProgressBarColor()
                    .setReceivedTitleCallback { webView, s -> tvWebTitle.text = s }
                    .createAgentWeb()
                    .ready()
                    .go(intent.getStringExtra(WEB_URL))
            agentWeb?.jsInterfaceHolder?.addJavaObject(WEB_METHOD, HttpJavaScriptInterface(this@WebActivity))
            ivWebBack.setOnClickListener {
                finish()
                overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right)
            }
        }
    }

    override fun initClick() {
    }

    override fun doBusiness(what: Int, response: Response<String>) {

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        agentWeb?.let { return it.handleKeyEvent(keyCode, event) }
        return super.onKeyDown(keyCode, event)
    }

    override fun onPause() {
        agentWeb?.webLifeCycle?.onPause()
        super.onPause()
    }

    override fun onResume() {
        agentWeb?.webLifeCycle?.onResume()
        super.onResume()
    }

}
